<?php

class DefaultController extends CController
{
	public $breadcrumbs = array();

	public function actionIndex()
	{
		$owner = $this->findOwnerByAdviserInitials(Yii::app()->user->getState('dbuser')->initials);
		$projects = $this->findProjectsByOwnerId($owner->id);
		$this->render('index', array('projects' => $projects));
	}

	public function actionCreate() {
		$model = new Project();

		if (isset($_POST['Project'])) {
			$rb = false;
			$transaction = Yii::app()->db->beginTransaction();
			$owner = $this->findOwnerByAdviserInitials(Yii::app()->user->getState('dbuser')->initials);
			$model->attributes = $_POST['Project'];
			$model->owner_id = $owner->id;
			if ($model->validate() && $model->save()) {

				// create all project topic associated to route
				$route = $model->route;
				$topics = array();
				$ptopics = array();
				foreach ($route->steps as $step) {
					$topics = $topics + $step->topics;
				}

				while (count($topics) > 0) {
					$topic = array_pop($topics);
					if ($topic->topics != null && count($topic->topics) > 0) {
						$topics = $topics + $topic->topics;
					} else {
						$ptopic = new ProjectTopic();
						$ptopic->input_date = date(Constants::SQL_DATE_FORMAT);
						$ptopic->weeks_number = $topic->weeks_number;
						$ptopic->topic_id = $topic->id;
						$ptopic->project_id = $model->id;
						$ptopic->adviser_validation = 0;
						$ptopic->owner_validation = 0;
						$ptopic->objective = 0;
						$ptopics[] = $ptopic;
					}
				}

				foreach($ptopics as $ptopic) {
					if (!$ptopic->save()) {
						$rb = true;
						$model->addErrors($ptopic->getErrors());
					}
				}

				// create a meeting for today
				$meeting = new Meetings();
				$meeting->meeting_date = date(Constants::SQL_DATE_FORMAT);
				$meeting->project_id = $model->id;
				if (!$meeting->validate() || !$meeting->save())
				$rb = true;

				if ($rb)
				$transaction->rollback();
				else  {
					$transaction->commit();
					$this->redirect(array ('show', 'id' => $model->id));
					return;
				}
			} else {
				$transaction->rollback();
			}
		}

		$this->render('form', array('model' => $model));
	}

	public function actionShow() {
		$project = Project::model()->findByPk($_GET['id']);
		
		if ($project == null) {
			header('HTTP/1.1 404 Not found');
			return;
		}
		
		if ($project->owner->adviser_initials != Yii::app()->user->getState('dbuser')->initials) {
			header('HTTP/1.1 403 Forbidden');
			return;
		}

		$this->render('show', array('project' => $project));
	}

	public function actionGauge() {
		/*Ici, on récupère dans la variable $pc le pourcentage que l'on veut afficher la page est appelée par compteur.php?pc=[un nombre entre 0 et 100]*/
		if(isset($_GET['pc']))
		{
			$pc=$_GET['pc'];
		}
		 
		/*Ici, on récupère dans la variable $pc le pourcentage que l'on veut afficher la page est appelée par compteur.php?pc=[un nombre entre 0 et 100]*/
		$width=150;
		if(isset($_GET['width']))
		{
			$width=(int)$_GET['width'];
			if ($width <= 0)
				$width=150;
		}
		$height=15;
		if(isset($_GET['height']))
		{
			$height=(int)$_GET['height'];
			if ($height <= 0)
				$height=15;
		}
		
		/*cette fonction indique que la page devra etre interprétée comme une image PNG*/
		header ("Content-type: image/png");

		/*on crée une image de 150 pixels de large sur 15 de haut*/
		$image = imagecreate($width, $height);
		 
		/* pour une image de 150 px, la partie à remplire en pourcentage fait 148px... on calcule la longueur à remplir en pixels */
		$x=($pc*($width-2))/100;
		 
		/*définition des couleurs... l'image est automatiquement remplie avec la première couleur que vous définissez. Ici on aura un fond blanc */
		$blanc=imagecolorallocate($image, 255, 255, 255);
		$noir=imagecolorallocate($image, 0, 0, 0);
		$bleu=imagecolorallocate($image, 170, 204, 238);
		 
		/*on fait un petit cadre noir sur le pourtour de l'image*/
		imagerectangle($image, 0, 0, $width-1, $height-1, $noir);

		/*dessin du remplissage en fonction de $x : on dessine un rectangle de $x pixels de large rempli en bleu*/
		if ($pc > 0) 
			imageFilledRectangle($image, 1, 1, $x, $height-2, $bleu);

		/*on place le texte au milieu : [$pc %]...*/
		imagestring($image, 3, ($width/2)-10, (($height-13)/2), $pc."%", $noir);

		/*Pour finir, on génère l'image en png§ */
		imagepng($image);
	}

	protected function findOwnerByAdviserInitials($initials) {
		return Owner::model()->find("adviser_initials = :initials", array(':initials' => $initials));
	}

	protected function findProjectsByOwnerId($owner_id) {
		return Project::model()->findAll("owner_id = :owner_id", array('owner_id' => $owner_id));
	}

	protected function createProjectTopic($meeting, $project, $topic_id) {
		$ptopic = ProjectTopic::model()->findByAttributes(array (
			'project_id' => $project->id,
			'topic_id' => $topic_id
		));
		if ($ptopic == null) {
			$ptopic = new ProjectTopic();
			$ptopic->input_date = date(Constants::SQL_DATE_FORMAT);
			$ptopic->project_id = $project->id;
			$ptopic->topic_id = $topic_id;
		}
		$ptopic->adviser_validation = (isset ($this->adviser[$topic_id]) && $this->adviser[$topic_id] == true ? Constants::TRUE : Constants::FALSE);
		if ($ptopic->adviser_validation == Constants::TRUE) {
			if ($ptopic->adviser_validation_date == null || $ptopic->adviser_validation_date == "")
			$ptopic->adviser_validation_date = $meeting->meeting_date;
		} else {
			$ptopic->adviser_validation_date = null;
		}

		$ptopic->owner_validation = (isset ($this->owner[$topic_id]) && $this->owner[$topic_id] == true ? Constants::TRUE : Constants::FALSE);
		if ($ptopic->owner_validation == Constants::TRUE) {
			if ($ptopic->owner_validation_date == null || $ptopic->owner_validation_date == '')
			$ptopic->owner_validation_date = $meeting->meeting_date;
		} else {
			$ptopic->owner_validation_date = null;
		}
		$ptopic->validation_comments = (isset ($this->comment[$topic_id]) ? $this->comment[$topic_id] : "");
		$ptopic->objective = Constants::FALSE;
		$ptopic->adviser_validation_topic = null;
		$ptopic->owner_validation_topic = null;

		return $ptopic;
	}

}